#!/usr/bin/env python
# -*- coding: utf8 -*-

'''
Created on 2011-7-26

京东价格图片识别模块

@author: zhongfeng
'''

import ImageFilter, ImageChops
from captcha_price import *
from coo8.coo8_feature2 import COO8_FEATURES_MAP
import Image
import itertools
import re
import time

try:
    import psyco
    psyco.full()
except ImportError:
    pass

class CaptchaProfile_coo8(CaptchaProfile):
    
    def __init__(self):
        pass
    def __new__(cls):
        '''
                    单态实现，初始化一次 
        '''
        if '_inst' not in vars(cls):
            cls.__catagory_FEATURES_MAP__ = dict([(feature_to_data(key),value) for key,value in COO8_FEATURES_MAP.iteritems()])
            cls._inst = super(CaptchaProfile_coo8, cls).__new__(cls)
        return cls._inst

    def filter(self, im):
        return im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1')

    def split(self, im):
        xsize, ysize = im.size
        pixels = im.load()
        zeroArr = []
        for x in xrange(xsize):
            flag = True
            for y in xrange(ysize):
                if pixels[x,y] != 255:
                    flag = False
                    break
            if flag:
                zeroArr.append(x)
        zeroArr = [(value - index ,value) for index,value in enumerate(zeroArr)]
        retd = []
        for key, group in itertools.groupby(zeroArr, lambda x: x[0]):
            ret = [t[1] for t in group]
            retd.append((ret[0],ret[-1]))
        l = len(retd)
        i = 0
        dd = []
        while i < l - 1 :
            pre = retd[i][1] + 1
            next = retd[i + 1][0]
#            if 2 < next - pre < 7:
#                nPre = retd[i + 1][1]
#                nNext = retd[i + 2][0]
#                if 2 < nNext - nPre < 7:
#                    dd.append((pre,4,nNext,16))
#                    i = i + 2
#                    continue
#            print (pre,4,next,16)
            dd.append((pre,4,next,16))
            i = i + 1
        return (im.crop(idt) for idt in dd[1:])

    def match(self, im):
        st = time.time()
        imageData = feature_to_data(CaptchaImageAlgorithm.GetBinaryMap(im))
        
        result = self.__catagory_FEATURES_MAP__.get(imageData,None)
        if result != None:
            return result
        print CaptchaImageAlgorithm.GetBinaryMap(im),'\n'
        source = im.getdata()
        algorithm = CaptchaAlgorithm()
        minimal = min(COO8_FEATURES_MAP, key=lambda feature:algorithm.LevenshteinDistance(source, feature_to_data(feature)))
        return COO8_FEATURES_MAP[minimal]

def captcha_coo8(filename):
    return captcha(filename, CaptchaProfile_coo8())

def test():
    print CaptchaProfile_coo8(r'c:\gp359329,2.png')
    
import os  
curModDir = os.path.dirname(os.path.abspath(__file__))
testFilePath = os.path.join(curModDir, 'test_resources')
if __name__ == '__main__':
    fileName = os.path.join(testFilePath, "125487,1.png")
    print captcha_coo8(fileName)
    
#    it1 = im.crop((3, 4, 13, 16))
#    print cia.GetBinaryMap(it1),'\n'
#    it2 = im.crop((15,4,24,16))
#    print cia.GetBinaryMap(it2)
#    print '+++++++++'
#    it2 = im.crop((25, 4, 34, 16))
#    it3 = im.crop ((36,4,45,16))
#    #it3 = im.crop((35, 4, 37, 16))
#    it4 = im.crop((38, 4, 47, 16))
#    it5 = im.crop((48, 4, 57, 16))
#    #it6 = im.crop((51, 3, 57, 11))
#    #it7 = im.crop((59, 3, 65, 11))
#    multilist = [[0 for col in range(5)] for row in range(3)]
#    print '\n'.join(( str(t) for t in multilist))
    #profile = CaptchaProfile_360Buy()
    
    #print captcha_360buy(r'c:\6.png')
        
        
